//
//  PlantsHomeViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 27/03/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "PlantsHomeViewController.h"
#import "AppDelegate.h"
#import "PlantsListViewController.h"
#import "PlantSet.h"
#import "ViewPlantSetTableViewController.h"
#import "UITableView+TableSectionHeaderText.h"
#import "UITableViewCell+TextFont.h"
#import "PlantSet+CRUD.h"
#import "MKNumberBadgeView.h"
#import "SavePlantSetTableViewController.h"
#import "UILabel+TextFont.h"

@interface PlantsHomeViewController()
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic, strong) MKNumberBadgeView *badgeView;
@property (nonatomic, strong) NSArray *plantSets;
@end

@implementation PlantsHomeViewController
@synthesize context = _context;
@synthesize badgeView = _badgeView;
@synthesize plantSets = _plantSets;

#define NUMBER_OF_STATIC_CELLS  4

/*Search for a list of Planting sets*/
- (void)searchPlantSets {
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"PlantSet"];
    NSSortDescriptor *sorter = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    request.sortDescriptors = [NSArray arrayWithObject:sorter];
    NSError *error;
    self.plantSets = [self.context executeFetchRequest:request error:&error];
}


#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context = [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext];
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"plants_bg.png"]];
    [tempImageView setFrame:self.tableView.frame]; 
    self.tableView.backgroundView = tempImageView;
    
    //Set up the planting sets badge view
    self.badgeView = [[MKNumberBadgeView alloc] init];
    self.badgeView.hideWhenZero = YES;
}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self searchPlantSets];
    //Reload the table data to refresh the list of planting sets each time the view appears
    [self.tableView reloadData];
    
    //Set up the badge for set count
    CGRect frame = CGRectMake(220, 3, 40, 35);
    self.badgeView.frame = frame;
    [self.navigationController.navigationBar addSubview:self.badgeView];
    self.badgeView.value =[PlantSet countPlantsPlantSetArray];
    self.badgeView.fillColor = [UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1];

}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.badgeView removeFromSuperview];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //In section we have 4 static cells
    if(section == 0){
        return  NUMBER_OF_STATIC_CELLS;
    }else{
        //If we have no plant sets we still have one value in the list. This is the cell that tells the user
        //how to add a planting set
        if([self.plantSets count] == 0){
            return 1;
        }
        return [self.plantSets count];
    }
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if(section == 0){
        return @"Plant Finder";
    }else{
        return @"Planting Sets";
    }
}

/*Method that overrides CoreDataTableViewController to change the section in the indexPath. This is needed because
 we have more than one section on a screen*/
-(NSIndexPath *)changeSectionInIndexPath:(NSIndexPath *)newIndexPath forObjectIfRequired:(id)anObject
{
    if([anObject isKindOfClass:[PlantSet class]]){
        //PlantSet is in sesction 1, so we want to tell the tableview that any updates to that object should go into section 1.
        //This means that section 0 will remain static and it wont check the number of rows in that section after an update.
        return [NSIndexPath indexPathForRow:newIndexPath.row inSection:1];
    }
    return newIndexPath;
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"a2zSegue"]){
        [segue.destinationViewController setContext:self.context];
        [segue.destinationViewController setPredicate:nil];
        [segue.destinationViewController setSectionName:@"uppercaseFirstLetterOfName"];
        [segue.destinationViewController setSortProperty:@"name"];
        [segue.destinationViewController setTitle:@"Plants A-Z"];
        
    } else if([segue.identifier isEqualToString:@"categoriesSegue"]){
        [segue.destinationViewController setContext:self.context];
        [segue.destinationViewController setPredicate:nil];
        [segue.destinationViewController setSectionName:@"category"];
        [segue.destinationViewController setSortProperty:@"category"];
        [segue.destinationViewController setTitle:@"Categories"];
        
    } else if([segue.identifier isEqualToString:@"seasonsSegue"]){
        [segue.destinationViewController setContext:self.context];
        [segue.destinationViewController setPredicate:nil];
        [segue.destinationViewController setSectionName:@"season"];
        [segue.destinationViewController setSortProperty:@"season"];
        [segue.destinationViewController setTitle:@"Planting Season"];
        
    } else if([segue.identifier isEqualToString:@"favouritesSegue"]){
        [segue.destinationViewController setContext:self.context];
        [segue.destinationViewController setPredicate:[NSPredicate predicateWithFormat:@"isFavourite = %d", 1]];
        [segue.destinationViewController setSectionName:nil];
        [segue.destinationViewController setSortProperty:@"name"];
        [segue.destinationViewController setTitle:@"Favourites"];
        
    }else if([segue.identifier isEqualToString:@"viewPlantSetSegue"]){   
        [segue.destinationViewController setPlantSet:sender];
    }else if([segue.identifier isEqualToString:@"addToExistingPlantSetSegue"]){
        UINavigationController *navCon = (UINavigationController *)segue.destinationViewController;
        SavePlantSetTableViewController *savePlantSetVC = [navCon.viewControllers objectAtIndex:0];
        savePlantSetVC.addtoExistingPlantSet = YES;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1 && [self.plantSets count] == 0){
        return 86;
    }
    return 44;
}

-(UITableViewCell *)buildStaticCellsForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier;
    switch (indexPath.row) {
        case 0:
            cellIdentifier = @"A2Z";
            break;
        case 1:
            cellIdentifier = @"categories";
            break;
        case 2:
            cellIdentifier = @"seasons";
            break;
        case 3:
            cellIdentifier = @"favourites";
            break;
        default:
            break;
    }
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    [cell setSketchBlockFont];
    return cell;
}

-(UITableViewCell *)buildPlantSetCellsForTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath
{
     static NSString *cellIdentifier;
    if([self.plantSets count] == 0){
        cellIdentifier = @"zeroSets";
    }else{
        cellIdentifier = @"setCell";
    }

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
   
    if([self.plantSets count] != 0){
        PlantSet *plantSet = [self.plantSets objectAtIndex:indexPath.row];
        cell.textLabel.text = plantSet.name;
        [cell setSketchBlockFont];
    }else {        
        UILabel *titleLabel = (UILabel *)[cell viewWithTag:1];
        [titleLabel setSketchBlockFont];
        
        UILabel *detailLabel = (UILabel *)[cell viewWithTag:2];
        [detailLabel setMVBoliFont];
       
    }
        
    return cell;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row < NUMBER_OF_STATIC_CELLS && indexPath.section == 0) {
        return [self buildStaticCellsForTableView:tableView atIndexPath:indexPath];
    } else {
        return [self buildPlantSetCellsForTableView:tableView atIndexPath:indexPath];
    }
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 1){
        Plant *selectedPlant = [self.plantSets objectAtIndex:indexPath.row];
        [self performSegueWithIdentifier:@"viewPlantSetSegue" sender:selectedPlant];
    }
}

/*Create a custom header view for each section*/
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    NSString *sectionTitle = [self tableView:self.tableView titleForHeaderInSection:section]; 
    return [UITableView createSectionHeaderTextLabel:sectionTitle];
}


- (IBAction)saveSetPressed:(UIBarButtonItem *)sender 
{
    NSMutableArray *plantSetArray = [PlantSet getPlantSetFromNSUserDefaults];
    //Show an alert if there are no plants in the NSUserDefualts plant set array
    if(plantSetArray == nil || [plantSetArray count] == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"There is nothing to save! Please add a plant to the Planting Set first" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        NSString *addToExistingText;
        if ([[PlantSet getAllPlantSetsInContext:self.context] count] != 0) {
            addToExistingText = @"Add to existing Set";
        }
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Create new Set", addToExistingText, nil];
        
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
        [actionSheet showFromTabBar:self.tabBarController.tabBar];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[PlantSet getAllPlantSetsInContext:self.context] count] != 0) {
        switch (buttonIndex) {
            case 0:
                [self performSegueWithIdentifier:@"savePlantSetSegue" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"addToExistingPlantSetSegue" sender:self];
                break;
            default:
                break;
        }
    }else{
        switch (buttonIndex) {
            case 0:
                [self performSegueWithIdentifier:@"savePlantSetSegue" sender:self];
                break;
                
            default:
                break;
        }
    }
}

@end
